<?php
/*
Copyright (C) 2011  Benjamin Marchand

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
class PublicController extends Controller {
	var $helpers = array('Paginator','Html','Javascript','Session','Js' => array('jquery'));
	var $components = array('RequestHandler','Session','Minelink','Remotetoolkit','Auth');
	var $uses = array('item','User','mcuser','mcgroup','mcright','Setting','mctemplateplugin'); 
	var $view = 'Theme';

	function isAuthorized()
	{
		return TRUE;
	}
	
	function beforeRender()
	{
		parent::beforeRender();
		$theme = Configure::read('bukkitadmin.theme');
		if (!empty($theme))
		{
			$this->theme = $theme;
		}
		

	}
	
	function logout()
	{
		$this->Session->setFlash("You’ve successfully logged out.");
		$this->redirect($this->Auth->logout());
	}
	
	function beforeFilter(){
		//reads the site-wide config values from the DB and puts them through the Configure::write method
		$this->Setting->getcfg();
		$this->Auth->allow("*");
		$mappublicview = Configure::read('bukkitadmin.mappublicview');
		$statspublicview = Configure::read('bukkitadmin.statspublicview');
		$mapregisteredview = Configure::read('bukkitadmin.mapregisteredview');
		$statsregisteredview = Configure::read('bukkitadmin.statsregisteredview');
		$group = $this->Auth->user('group');
		
		switch($this->params['action'])
		{
			case "showstats" :
				if ((empty($group) && (!$statspublicview)) || ($group==2 && !$statsregisteredview))
					exit();
				break;
			
			case "view_map" : 
				if ((empty($group) && (!$mappublicview)) || ($group==2 && !$mapregisteredview))
					exit();
				break;
			default :
				break;
		}
	}
	
	function afterFilter(){
		//retrieves the site-wide configurations from Configure::read($key) and puts it back into the db if new
		$this->Setting->writecfg();
		} 

	function register() {
	if (!empty($this->data)) {
			$this->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
			$this->User->create();
			$this->User->save($this->data);
		}
	}
	
	function _pluginexist($plugin)
	{
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path .= DS.'plugins'.DS.$plugin.'.jar';
		if (file_exists($path))
			return TRUE;
		else
			return FALSE;
	}

	function index() {
		//$this->set('title_for_layout',"Webukkit");
		$websitename = Configure::read('bukkitadmin.websitename');
		if (!empty($websitename))
		{
			$this->set('title_for_layout',$websitename);
		}
		else
		{
			$this->set('title_for_layout','Webukkit');
			$this->set('version',Configure::read('version'));
		}
		$mappublicview = Configure::read('bukkitadmin.mappublicview');
		$statspublicview = Configure::read('bukkitadmin.statspublicview');
		$mapregisteredview = Configure::read('bukkitadmin.mapregisteredview');
		$statsregisteredview = Configure::read('bukkitadmin.statsregisteredview');
		$group = $this->Auth->user('group');
		if ((empty($group) && ($mappublicview)) || ($group==2 && $mapregisteredview) || ($group==1))
			$this->set('showmap','true');
		if ($this->_pluginexist('Stats')) 
		{
			if ((empty($group) && ($statspublicview)) || ($group==2 && $statsregisteredview) || ($group==1))
				$this->set('showstats','true');
		}
		$this->set('lang',$this->Session->read('Config.language'));
	}
	
	function showstats()
	{
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path.= DS.'stats'.DS.'stats.db';
		if (file_exists($path))
		{
			$sqlite['driver']= 'sqlite3';
			$sqlite['database']= $path;
			$db = ConnectionManager::create('stats',$sqlite);
	
			$this->loadModel('stat');
			// Show Last login
			$this->set('lastlogins',$this->stat->find('all',array('fields'=>array('player','value'),'order'=>'value DESC','limit'=>10,'conditions'=>array('stat'=>'lastlogin'))));
			// Show total time played
			$this->set('totaltime',$this->stat->find('all',array('fields'=>array('player','value'),'order'=>'value DESC','conditions'=>array('stat'=>'playedfor'))));
			// show top 10 block destroyers
			$this->set('totalblockdestroy',$this->stat->find('all',array('fields'=>array('player','value'),'order'=>'value DESC','limit'=>10,'conditions'=>array('stat'=>'totalblockdestroy'))));
			// show top 10 items pickers
			// show top 10 players who like to live
			// show top 10 block creaters
			$this->set('totalblockcreate',$this->stat->find('all',array('fields'=>array('player','value'),'order'=>'value DESC','limit'=>10,'conditions'=>array('stat'=>'totalblockcreate'))));
			// show top 10 chatters
			$this->set('chat',$this->stat->find('all',array('fields'=>array('player','value'),'order'=>'value DESC','limit'=>10,'conditions'=>array('stat'=>'chat'))));
			// show top 10 most travelers
			$this->set('move',$this->stat->find('all',array('fields'=>array('player','value'),'order'=>'value DESC','limit'=>10,'conditions'=>array('stat'=>'move'))));
			// show top 10 killers
			$this->set('kills',$this->stat->find('all',array('fields'=>array('player','value'),'order'=>'value ASC','conditions'=>array('stat'=>'total','category'=>'kills'))));
			$this->set('deaths',$this->stat->find('all',array('fields'=>array('player','value'),'order'=>'value ASC','conditions'=>array('stat'=>'total','category'=>'deaths'))));
			
			$this->set('damagetaken',$this->stat->find('all',array('fields'=>array('player','value'),'order'=>'value DESC','conditions'=>array('stat'=>'total','category'=>'damagetaken'))));
			$this->set('stats',$this->stat->find('all'));
		}
		else
		{
			$messages[] = array('image'=>'clear_icon.png','message'=>__('Stats database (stats.db) not found!',true));
			$this->set('messages',$messages);
			$this->render('/elements/message');
		}
	}
	
	function showplayers()
	{
		$this->autoLayout=FALSE;
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path.= DS.'stats'.DS.'stats.db';
		if (file_exists($path))
		{
			$sqlite['driver']= 'sqlite3';
			$sqlite['database']= $path;
			$db = ConnectionManager::create('stats',$sqlite);
			$this->loadModel('stat');
			//$this->set('statsplayers',$this->stat->find('all',array('order'=>'player')));
			$this->set('players',$this->stat->find('all',array('fields'=>array('DISTINCT player'))));
		}
		else
		{
			$messages[] = array('image'=>'clear_icon.png','message'=>__('Stats database (stats.db) not found!',true));
			$this->set('messages',$messages);
			$this->render('/elements/message');
		}
	}
	
	function showplayer($player)
	{
		$this->autoLayout=FALSE;
		$path = Configure::read('bukkitadmin.MinecraftPath');
		// We set the items list
		if (file_exists($path.DS.'items.txt'))
		{
			$data = file_get_contents($path.DS.'items.txt');
			$data = preg_split('/\r\n|\r|\n/',$data);
			
			foreach($data as $item)
			{
				if (!preg_match("/^#/",$item) && (trim($item)!=''))
				{
					$objects[]=explode(":",$item);
				}
			}
			foreach($objects as $object)
			{
					$items[$object[0]]=$object[1];
			}
		}
		$this->set('items',$items);
		$this->set('itemsdb',$this->item->find('list',array('fields'=>'image')));
		$path.= DS.'stats'.DS.'stats.db';
		if (file_exists($path) && (!empty($player)))
		{
			$sqlite['driver']= 'sqlite3';
			$sqlite['database']= $path;
			$db = ConnectionManager::create('stats',$sqlite);
			$this->loadModel('stat');
			$this->set('stats',$this->stat->findAllByPlayer($player));
		}
		else
		{
			$messages[] = array('image'=>'clear_icon.png','message'=>__('Stats database (stats.db) not found!',true));
			$this->set('messages',$messages);
			$this->render('/elements/message');
		}
	}
	
	function view_map()
	{
		$this->autoLayout = false;
		$this->set('Mapsystem',Configure::read('bukkitadmin.Mapsystem'));
		$this->set('Mapsystemparam',Configure::read('bukkitadmin.Mapsystemparam'));
	}
}

?>